package com.spring.jackson.seckill.controller;

import com.spring.jackson.seckill.cache.GoodsInfoCacheWorker;
import com.spring.jackson.seckill.cache.SeckillSuccessTokenCache;
import com.spring.jackson.seckill.model.Goods;
import com.spring.jackson.seckill.service.GoodsService;
import com.spring.jackson.smvc.annotation.RequestMapping;
import com.spring.jackson.smvc.enums.ReturnType;
import com.spring.jackson.smvc.util.Assert;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
@RequestMapping(value = "/interface/")
public class SeckillInterfaceController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsInfoCacheWorker goodsInfoCacheWorker;

    @Autowired
    private SeckillSuccessTokenCache seckillSuccessTokenCache;

    /**
     * 秒杀入口
     *
     * @param mobile
     * @param goodsRandomName
     * @return
     */
    @RequestMapping(value = "startSeckill", returnType = ReturnType.JSON)
    public String startSeckill(String mobile, String goodsRandomName) {
        Assert.notNull(goodsRandomName);
        Assert.notNull(mobile);

        goodsService.seckill(mobile, goodsRandomName);
        //暂时先返回mobile
        return mobile;
    }

    /**
     * 获取秒杀商品的链接
     *
     * @return
     */
    @RequestMapping(value = "{goodsId}/getSeckillGoodsLink", returnType = ReturnType.JSON)
    public String getSeckillGoodsLink(Integer goodsId) {
        //先从redis缓存中取商品信息，没有取到时去DB查，然后存入缓存
        Goods goods = goodsInfoCacheWorker.get(goodsId, Goods.class);
        long now = System.currentTimeMillis();
        // 已经开始了活动，则输出抢购链接
        if (goods.getStartTime().getTime() < now && now < goods.getEndTime().getTime()) {
            return goods.getRandomName();
        }

        return StringUtils.EMPTY;
    }

    /**
     * 查询秒杀结果
     *
     * @param mobile
     * @param goodsRandomName
     * @return
     */
    @RequestMapping(value = "seckillResult", returnType = ReturnType.JSON)
    public String seckillResult(String mobile, String goodsRandomName) {

        return seckillSuccessTokenCache.queryToken(mobile, goodsRandomName);
    }

    /***
     * 下单，真正的扣减DB库存，
     * @param mobile
     * @param goodsId
     * @param token
     * @return
     */
    @RequestMapping(value = "order", returnType = ReturnType.JSON)
    public Integer order(String mobile, Integer goodsId, String token) {
        return goodsService.order(mobile, goodsId, token);
    }


    /**
     * 获取当前系统时间(毫秒)
     *
     * @return
     */
    @RequestMapping(value = "time/now", returnType = ReturnType.JSON)
//    @ResponseBody
    public Long time() {
        return System.currentTimeMillis();
    }
}
